//
//  MyView.m
//  九宫格
//
//  Created by mj on 14-9-9.
//  Copyright (c) 2014年 Mr.Li. All rights reserved.
//
#import "RNGridMenu.h"
#import "MyView.h"
#import "Model.h"
#import "MHFileTool.h"
#import "M_shop.h"
#import "ContentViewController.h"
#import "jingtai.h"

#import "MainViewController.h"

#import "DES.h"
#import "UIDeviceMeasure1.h"
#import "/Users/dengzeyu/Documents/projectiOS /cardmenNew/cardmenNew/Helper/UIImage_imageScale.h"
#import "shopView/ShopViewController.h"
#import "Downloaddata.h"
#import "MHFileTool.h"

@implementation MyView
BOOL isfirst=YES;
-(NSInteger) getsizeof
{
    UIDeviceMeasure1 *device = [[UIDeviceMeasure1 alloc]init];
    switch ([device identifyResolution ]) {
        case UIDevice_iPad:
        {
            NSLog(@"ipad");
            return 160;
            break;
        }
            
        case UIDevice_iPhone4_4s:
        {
            NSLog(@"iphone4");
            return 84;
            break;
        }
        case UIDevice_iPhone5_5s:
        {
            NSLog(@"ip5");
            return 86;
            break;
        }
        case UIDevice_iPhone6:
        {
            NSLog(@"ip6");
            return 90;
            break;
        }
        case UIDevice_iPhone6plus:
        {
            NSLog(@"ip6p");
            return 94;
            break;
        }
    default:
            return  0;
            
    }
}
-(NSString *)getcachesdirection
{
    NSArray * a=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [a objectAtIndex:0];

}
-(NSString *)getdocpath
{
    NSArray * a=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [a objectAtIndex:0];

}

- (id)initWithFrame:(CGRect)frame Model:(Model *)model MyButtonBlock:(MyButtonBlock)myButtonBlock
{
    myButtonBlock = myButtonBlock;
    _model = model;
    self = [super initWithFrame:frame];
    if (self)
    {
        CGFloat W = frame.size.width;
        _imageView = [[UIImageView alloc] init];
        _button = [[UIButton alloc] init];
        CGFloat imageViewX =0;
        CGFloat imageViewY = 0;
        CGFloat imageViewW = W;
        CGFloat imageViewH = frame.size.height;
        self.frame=CGRectMake(frame.origin.x, frame.origin.y, imageViewW, imageViewH);
       
        _button.frame = CGRectMake(imageViewX, imageViewY, imageViewW, imageViewH);
//        [_button setBackgroundImage:[jingtai getImageFromURL:model.Icon andislocal:NO]  forState:UIControlStateNormal];
//        [_button setBackgroundImage:[jingtai getImageFromURL:model.Icon andislocal:NO]  forState:UIControlStateNormal];
        CGFloat imagesize = _button.frame.size.height<=_button.frame.size.width?_button.frame.size.height:_button.frame.size.width;
        if(_button.frame.size.height<=_button.frame.size.width)
        {
            _button.frame= CGRectMake((imageViewW-imageViewH)/2.0, 0, _button.frame.size.height-1, _button.frame.size.height-1);
        }
        else
        {
            _button.frame= CGRectMake(0, (imageViewH-imageViewW)/2.0, _button.frame.size.width-1, _button.frame.size.width-1);

        }
        dispatch_queue_t queue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            UIImage * image;
            
            switch (model.kind) {
                case 0:
                {
                    [_button addTarget:self action:@selector(tapButton) forControlEvents:UIControlEventTouchUpInside];
                    if([[jingtai getlocalkindversion] isEqualToString:[jingtai sharedSingleton].kindversion])
                    {
                        image =[jingtai getImageFromURL:model.Icon andislocal:NO andismustdonwload:NO];
                        
                    }
                    else{
                        image =[jingtai getImageFromURL:model.Icon andislocal:NO andismustdonwload:YES];
                    }
                 
                }
                    break;
                case 1:
                {
                    [_button addTarget:self action:@selector(tapButtonshop) forControlEvents:UIControlEventTouchUpInside];
                    
                    if([[jingtai getlocalshopversion] isEqualToString:[jingtai sharedSingleton].shopversion])
                    {
                        image =[jingtai getImageFromURL:model.Icon andislocal:NO andismustdonwload:NO];
                        
                    }
                    else{
                        image =[jingtai getImageFromURL:model.Icon andislocal:NO andismustdonwload:YES];
                    }
                    NSLog(@"公司名字：%@,点赞数目：%@",model.name,((M_shop *)model).zan);
              
                }
                    break;
                case 2:
                {
                    [_button addTarget:self action:@selector(tapButtoncontent) forControlEvents:UIControlEventTouchUpInside];
                    if([[jingtai getlocalcontentversion] isEqualToString:[jingtai sharedSingleton].contentversion])
                    {
                        image =[jingtai getImageFromURL:model.Icon andislocal:NO andismustdonwload:NO];
                        
                    }
                    else{
                        image =[jingtai getImageFromURL:model.Icon andislocal:NO andismustdonwload:YES];
                    }
             
                    NSLog(@"内容图片 名字 %@",((M_content *)model).name);
                }
                    break;
                default:
                    break;
            }
               image  =[image TransformtoSize:CGSizeMake(imagesize*[[UIScreen mainScreen] scale], imagesize*[[UIScreen mainScreen] scale])];
            dispatch_async(dispatch_get_main_queue(), ^
                           {
                               [_imageView setExclusiveTouch:YES];
                               _imageView.frame = _button.frame;
                               [_imageView setImage:image];
                               [_button setExclusiveTouch:YES];
                               [_button setBackgroundImage:image forState:UIControlStateNormal];
                               [_button.imageView setContentMode:UIViewContentModeCenter];
                               [self addSubview:_button];
                               [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate date]];
                           });
           

        });
      
           }
    return self;
}
- (void)tapButtoncontent
{
    M_content * model = (M_content *)self.model;
    switch (model.state) {
        case 0:
        {
            if([model.Zhuangtai isEqualToString:@"1"])
            {
            Downloaddata * down =[[Downloaddata alloc] init];
            [down star:model.Lujing andModel:model andmyView:self];
            }
            else
            {
                NSLog(@"需要验证");// 二维码验证接口！
            }
        }
        break;
        case 1:
        {
            NSLog(@"传入unity路径：%@",[MHFileTool getCacheFile:model.localPath]);
        }
        break;
        case 2:
        {
            NSLog(@"更新");
            Downloaddata * down =[[Downloaddata alloc] init];
            [down star:model.Lujing andModel:model andmyView:self];
        }
            break;
        case 3:
        {
            NSLog(@"删除");
            NSFileManager * filem = [NSFileManager defaultManager];
            NSString * path =[MHFileTool getCacheFile:[NSString stringWithFormat:@"/%@/%@/%@",model.kindname,model.shopname,model.name]];
            [filem removeItemAtPath:path error:nil];
            NSFileManager * fm = [NSFileManager defaultManager];
            NSString * download =[MHFileTool getLocalFilePath:@"downloaded.plist"];
            NSMutableArray * dic = [[NSMutableArray alloc] initWithContentsOfFile:download];
            for (NSDictionary * tempdic in dic) {
                if([model check:model andtwo:tempdic]==1)
                {
                    [dic removeObject:tempdic];
                }
            }
            [dic writeToFile:download atomically:YES];
            if([jingtai sharedSingleton].contentview.leixing==1)
            {
                 [[jingtai sharedSingleton].contentview selectappList:[jingtai sharedSingleton].contentview.currentKind andisdelete :NO];
                
                [[jingtai sharedSingleton].contentview loadscroll];
                [jingtai sharedSingleton].contentview.isdelete=NO;
                [[jingtai sharedSingleton].contentview.shanchu  setImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];

            }
           else
           {
               [[jingtai sharedSingleton].contentview loadscroll:NO];

            [jingtai sharedSingleton].contentview.isdelete=NO;
           [[jingtai sharedSingleton].contentview.shanchu  setImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
           }
        }
            break;
        default:
            break;
    }
    NSLog(@"content tap");
}
- (void)tapButtonshop
{
    ContentViewController * ck ;
    NSLog(self.model.name);
    UIDeviceMeasure1 *device = [[UIDeviceMeasure1 alloc]init];
    switch ([device identifyResolution ]) {
        case UIDevice_iPad:
        {
            NSLog(@"ipad");
            UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:@"content" bundle:nil];
            ck=[storyBoard instantiateViewControllerWithIdentifier:@"ipad"];
          
            break;
            
        }
            
        case UIDevice_iPhone4_4s:
        {
            NSLog(@"iphone4");
            UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:@"content" bundle:nil];
            ck=[storyBoard instantiateViewControllerWithIdentifier:@"iphone4"];
      
            break;
            
        }
        case UIDevice_iPhone5_5s:
        {
            NSLog(@"ip5");
            UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:@"content" bundle:nil];
            ck=[storyBoard instantiateViewControllerWithIdentifier:@"iphone5"];

            break;
        }
        case UIDevice_iPhone6:
        {
            NSLog(@"ip6");
            UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:@"content" bundle:nil];
            ck=[storyBoard instantiateViewControllerWithIdentifier:@"iphone6"];
            
            break;
        }
        case UIDevice_iPhone6plus:
        {
            NSLog(@"ip6p");
            UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:@"content" bundle:nil];
            ck=[storyBoard instantiateViewControllerWithIdentifier:@"ChoseViewcontroller"];
            
            break;
        }
            
    }
    ck.kindname= [jingtai sharedSingleton].shopview.kind;
    ck.shopname=self.model.name;
    ck.userid =((M_shop *)self.model).comid;
    ck.leixing =0;
    [[jingtai sharedSingleton].shopview presentViewController:ck animated:YES completion:nil];
}
- (void)tapButton
{
       NSLog(@"miaoshu:%@  lujing:%@",self.model.name,self.model.Icon);
    UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ShopViewController * shopViewController = [storyboard instantiateViewControllerWithIdentifier:@"shop"];
    shopViewController.kind=self.model.name;
    [[jingtai sharedSingleton].kindview.navigationController pushViewController:shopViewController animated:YES];
    [[jingtai sharedSingleton].kindview.myTopic releaseTimer];
}
- (void)showGriddelete :(CGPoint) point {
  }

- (void)showGrid :(CGPoint)point andisupdate:(BOOL)isupdate {
  
   }
-(void)shiyong
{
    
}
-(BOOL) isVerification: (NSString*)Kamengname
{
    NSString * pathVerification= [MHFileTool getLocalFilePath:@"Verification"];
    [MHFileTool createDirWithDirPath:pathVerification];
    if([MHFileTool isExistsFileInDoc:@"Verification/textofmessage.txt"])
    {
        NSString * message=[self getVerifictationmessage];
        
                NSArray *datas=[message componentsSeparatedByString:@"&"];
        NSArray * shebeimaarr=[[NSArray alloc] initWithArray:[[datas objectAtIndex:0] componentsSeparatedByString:@"∑"]];
        NSString * shebeima= [shebeimaarr objectAtIndex: 0];
        shebeima=[DES decryptWithText:shebeima];
        NSLog(@"设备码：%@        %@   ",shebeima,[jingtai sharedSingleton].shebeima);
        if([shebeima isEqualToString:[jingtai sharedSingleton].shebeima])
        {
            NSArray * KamengGifts=[[datas objectAtIndex:1] componentsSeparatedByString:@";"];
        
            for(NSString * Kamengnametemp in KamengGifts)
            {
                if([Kamengname isEqualToString:Kamengnametemp])
                {
                    return YES;
                }
            }
            return NO;
        
        }
        else
        {
            [MHFileTool deletefile:[pathVerification stringByAppendingPathComponent:@"/textofmessage.txt"]];
            return NO;
        }
    }
    else
        
        
    {
    return NO;
    }
}
-(BOOL) isexiteofverificationfile
{
    if([MHFileTool isExistsFileInDoc:@"Verification/textofmessage.txt"])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
-(NSString *) getVerifictationmessage
{
      NSString * pathVerification= [MHFileTool getLocalFilePath:@"Verification"];
    NSString * Verificationmessage=[NSString stringWithContentsOfFile:[pathVerification stringByAppendingPathComponent:@"/textofmessage.txt"] encoding:NSUTF8StringEncoding error:nil];
    NSString * message= [DES decryptWithText:Verificationmessage];
    return message;
}
-(void) writetomessage : (NSString*) message
{
    NSString * pathVerification= [MHFileTool getLocalFilePath:@"Verification"];

    if([MHFileTool isExistsFileInDoc:@"Verification/textofmessage.txt"])
    {
        [message writeToFile:[pathVerification stringByAppendingPathComponent:@"/textofmessage.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    else
    {
       [message writeToFile:[pathVerification stringByAppendingPathComponent:@"/textofmessage.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }

}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
  

}
- (BOOL)shouldAutorotate
{
    return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

@end
